package com.attilax.secury;
import java.security.Key; 

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 
 


import org.apache.commons.codec.binary.Base64;

import com.attilax.text.strUtil;
  
public class CryptAES { 
  
    private static   String AESTYPE ="AES/ECB/PKCS5Padding"; 
 
    public static String AES_Encrypt(String plainText,String keyStr) { 
        byte[] encrypt = null; 
        try{ 
            Key key = generateKey(keyStr);
       //     AESTYPE="AES";  when use thie and same with  AESTYPE ="AES/ECB/PKCS5Padding"; 
            Cipher cipher = Cipher.getInstance(AESTYPE); //
            cipher.init(Cipher.ENCRYPT_MODE, key); 
            encrypt = cipher.doFinal(plainText.getBytes());     
        }catch(Exception e){ 
            e.printStackTrace(); 
            throw new RuntimeException(e);
        }
        return new String(Base64.encodeBase64(encrypt)); 
    } 
 
    public static String AES_Decrypt(String keyStr, String encryptData) {
        byte[] decrypt = null; 
        try{ 
            Key key = generateKey(keyStr); 
            Cipher cipher = Cipher.getInstance(AESTYPE); 
            cipher.init(Cipher.DECRYPT_MODE, key); 
            decrypt = cipher.doFinal(Base64.decodeBase64(encryptData)); 
        }catch(Exception e){ 
            e.printStackTrace(); 
        } 
        return new String(decrypt).trim(); 
    } 
 
    
    
 
    
    private static Key generateKey(String key)throws Exception{ 
        try{    
        	
//        	if(key.length()<16)
//        	{
//        		  key=strUtil.str_pad0(key, 16);
//        	}
        	key=MD5.getMD5_16bit(key,"utf-8");
            byte[] bytes = key.getBytes();
          
			SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES"); 
            return keySpec; 
        }catch(Exception e){ 
            e.printStackTrace(); 
            throw e; 
        } 
 
    } 
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
 
    public static void main(String[] args) { 
         
        String keyStr = "123456汉字";    //java.security.InvalidKeyException: Invalid AES key length: 6 bytes
        //f/Rps4dZr9CMHnsm6U8bBg==
        //f/Rps4dZr9CMHnsm6U8bBg==
      //  f/Rps4dZr9CMHnsm6U8bBg==
        //f/Rps4dZr9CMHnsm6U8bBg==
 
        String plainText = "abc";
        //ucSL5R/jQigQ1dxzsWi2kg==
     //   $keyStr = '1234567812345678';  //ucSL5R/jQigQ1dxzsWi2kg==
         
        String encText = AES_Encrypt( plainText,keyStr);
        String decString = AES_Decrypt(keyStr, encText); 
         
        System.out.println(encText); 
        System.out.println(decString); 
 
    } 
}